package com.jy.appmarket.download;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;

import com.jy.appmarket.download.DownloadService.FileDownloadListener;
import com.jy.appmarket.utils.LogUtil;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2014年5月20日
 * @version 1.0
 */

public abstract class DownloadActivity extends FragmentActivity implements FileDownloadListener {
	private static final String TAG = "DownloadActivity";

	public interface AppAndDownloadListener {

		void onPackageInstalled(String pkgName);

		void onPackageUninstalled(String pkgName);

		void onDownloadCreated(DownloadItem di);

		void onDownloadRemoved(String id);

		void onDownloadChanged(DownloadItem di);

		void onProgressChanged(String id, long downloaded, long speed);
	}

	private List<AppAndDownloadListener> mListeners = new ArrayList<AppAndDownloadListener>();

	public void addFileListener(AppAndDownloadListener l) {
		// LogUtil.d(TAG, "addListener:" + l);
		if (l != null) {
			mListeners.add(l);
		}
	}

	public void removeFileListener(AppAndDownloadListener l) {
		// LogUtil.d(TAG, "removeListener:" + l);
		if (l != null) {
			mListeners.remove(l);
		}
	}

	public void clearFileListener() {
		if (mListeners != null) {
			mListeners.clear();
		}
	}

	private DownloadService mDLService;

	public DownloadService getDownloadService() {
		return mDLService;
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mDLService = ((DownloadService.DLServiceBinder) service).getService();
			mDLService.addFileDownloadListener(DownloadActivity.this);
			onFileDownloadServiceConnected(mDLService);
		}
	};

	private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				String pkgName = intent.getDataString();
				if (pkgName == null) {
					return;
				}
				if (pkgName != null && pkgName.length() > 0) {
					pkgName = pkgName.substring(pkgName.lastIndexOf(':') + 1);
				}
				// LogUtil.d(TAG, "packageName:" + packageName);

				if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
					onPackageInstalled(pkgName);
					for (AppAndDownloadListener l : mListeners) {
						l.onPackageInstalled(pkgName);
					}
				} else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
					onPackageUninstalled(pkgName);
					for (AppAndDownloadListener l : mListeners) {
						l.onPackageUninstalled(pkgName);
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(mPackageReceiver, filter);
		bindService(new Intent(this, DownloadService.class), mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onDestroy() {
		if (mDLService != null) {
			mDLService.removeFileDownloadListener(this);
		}
		unbindService(mConnection);
		unregisterReceiver(mPackageReceiver);
		mListeners.clear();
		mListeners = null;
		super.onDestroy();
	}

	/**
	 * 如果需要准确知道{@link com.android.premarket.download.FileDownloadService}
	 * 绑定的时间请重载这个方法
	 * 
	 * @param service
	 */
	protected void onFileDownloadServiceConnected(DownloadService service) {
	}

	protected void onPackageInstalled(String pkgName) {

	}

	protected void onPackageUninstalled(String pkgName) {

	}

	@Override
	public void onProgressChanged(String id, long downloadedBytes, long speed) {
		if (TextUtils.isEmpty(id)) {
			return;
		}
		for (AppAndDownloadListener l : mListeners) {
			l.onProgressChanged(id, downloadedBytes, speed);
		}
	}

	/**
	 * di不会为null
	 */
	@Override
	public void onDownloadCreated(DownloadItem di) {
		for (AppAndDownloadListener l : mListeners) {
			l.onDownloadCreated(di);
		}
		LogUtil.d(TAG, "created:" + di.getName() + "   " + DownloadService.getStatusString(di.getStatus()));
	}

	/**
	 * di不会为null
	 */
	@Override
	public void onDownloadChanged(DownloadItem di) {
		for (AppAndDownloadListener l : mListeners) {
			l.onDownloadChanged(di);
		}
		LogUtil.d(TAG, "changed:" + di.getName() + "   " + DownloadService.getStatusString(di.getStatus()));
	}

	/**
	 * id不会为null
	 */
	@Override
	public void onDownloadRemoved(String id) {
		for (AppAndDownloadListener l : mListeners) {
			l.onDownloadRemoved(id);
		}
	}

	public boolean isDownloading(String pkgName, int versionCode) {
		if (mDLService == null) {
			return false;
		}
		return mDLService.isDownloading(pkgName, versionCode);
	}

	public boolean isDownloading(DownloadItem di) {
		if (mDLService == null) {
			return false;
		}
		return mDLService.isDownloading(di);
	}

	public int getDownloadStatus(String dlId, String pkgName, int verCode) {

		if (mDLService == null) {
			return DownloadService.STATUS_NO_STATUS;
		}

		return mDLService.getDownloadStatus(pkgName, verCode);
	}

	// 开始下载相关接口
	public final boolean addDownload(String dlUrl, String name, String pkgName, String versionName, int versionCode,
			String md5, String iconUrl, String source) {
		if (mDLService == null) {
			return false;
		}

		mDLService.addDownload(dlUrl, name, pkgName, versionName, versionCode, md5, iconUrl, source, 0, false);
		return true;
	}

	public void addWaitWifiDownload(String dlUrl, String name, String pkgName, String versionName, int versionCode,
			String md5, String iconUrl, String source) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return;
		}
		mDLService.addWaitWifiDownload(dlUrl, name, pkgName, versionName, versionCode, iconUrl, md5, source, 0, false);
	}

	public void addWaitWifiDownload(String dlUrl, String name, String pkgName, String versionName, int versionCode,
			String md5, String iconUrl, int priority, String source, boolean hidden) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return;
		}
		mDLService.addWaitWifiDownload(dlUrl, name, pkgName, versionName, versionCode, md5, iconUrl, source, priority,
				hidden);
	}

	public void startDownload(String dlId) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return;
		}
		mDLService.startDownload(dlId);
	}

	public void stopDownload(String dlId) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return;
		}
		mDLService.stopDownload(dlId);
	}

	public void installApk(final DownloadItem di) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return;
		}
		mDLService.installApk(di);
	}

	public final DownloadItem getDownloadById(String dlId) {
		if (mDLService == null) {
			LogUtil.d(TAG, "download service not inited");
			return null;
		}
		return mDLService.getDownloadById(dlId);
	}

	public List<DownloadItem> getAllDownloadsOrderBy(String colName, boolean isDesc) {
		if (mDLService == null) {
			return null;
		}
		return mDLService.getAllDownloadsOrderBy(colName, isDesc);
	}

	public void openApp(String pkgName) {
		try {
			Intent intent = getPackageManager().getLaunchIntentForPackage(pkgName);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void removeDownload(String dlId) {
		if (mDLService == null) {
			return;
		}

		mDLService.removeDownload(dlId);
	}

	public void removeOutofDateDownloads(String pkgName) {
		if (mDLService == null) {
			return;
		}

		mDLService.removeOutofDateDownloads(pkgName);
	}

	// public int removeAllInstalled() {
	// if (mDLService == null) {
	// LogUtil.d(TAG, "download service not inited");
	// return -1;
	// }
	// return mDLService.removeAllInstalled();
	// }

	public int removeAllInstalled(List<String> idList) {
		if (mDLService == null || idList == null || idList.size() == 0) {
			LogUtil.d(TAG, "download service not inited or idList is empty");
			return -1;
		}
		return mDLService.removeAllInstalled(idList);
	}

	public void removeDownloadFilesById(String dlId) {
		String path = DownloadUtils.getDownloadApkFilePathById(dlId);
		File fApk = new File(path);
		fApk.deleteOnExit();

		String tmpPath = DownloadUtils.getDownloadApkTmpFilePathById(dlId);
		File fTmp = new File(tmpPath);
		fTmp.deleteOnExit();
	}

	public long getDownloadedFileSizeById(String dlId) {
		String filePath = DownloadUtils.getDownloadApkTmpFilePathById(dlId);
		File f = new File(filePath);
		return f.length();
	}
}
